package com.travelingsalesmen.post.file;

import com.travelingsalesmen.post.*;
import com.travelingsalesmen.post.gui.GUIPost;
import com.travelingsalesmen.post.rmi.IServer;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class FilePost implements IPost {

    private Catalog catalog;
    private List<Invoice> newInvoices = new ArrayList<Invoice>();
    private IServer server;

    public FilePost() {
    }

    public void connectToServer(IServer server) {
        this.server = server;
    }

    public void getCatalogFromServer() throws RemoteException {
        this.catalog = server.getCatalog();
    }

    @Override
    public void setCatalog(Catalog catalog) {
        this.catalog = catalog;
    }

    @Override
    public Item scanItem(String upc, int quantity) {
        ProductSpec ps = catalog.getSpec(upc);
        return new Item(ps, quantity);
    }

    @Override
    /**
     * Start running the post. For a FilePost, we will iterate over the
     * transactions in the text file and process each one automatically.
     */
    public void start() {
        TransactionReader transactionReader = new TransactionReader(this);
        while (transactionReader.hasMoreTransactions()) {
            // Get the next transaction
            Transaction transaction = transactionReader.getNextTransaction();

            // Serve at this post
            transaction.setPost(this);

            // Finish Transaction
            transaction.pay();

            // Print receipt
            System.out.print(transaction);

            Invoice invoice = new Invoice(transaction);
            try {
                server.uploadInvoice(invoice);
                server.printInvoicesToFile();
            } catch (RemoteException ex) {
                // Server is down, add to local listing
                //System.out.println(ex);
                newInvoices.add(invoice);
            }
        }
    }

    /**
     * Try to upload any cached invoices and remove them if they are
     * successfully uploaded
     */
    public void uploadCachedInvoices() {
        if (newInvoices.isEmpty()) {
            // No cached invoices to upload
            return;
        }

        for (Invoice invoice : newInvoices) {
            try {
                server.uploadInvoice(invoice);
                newInvoices.remove(invoice);
            } catch (RemoteException ex) {
                Logger.getLogger(GUIPost.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
